package Principal;



import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import javax.swing.JOptionPane;

/**
 *
 * @author pato
 */
public class CerrarSesion extends javax.swing.JDialog {

    /**
     * Creates new form NewJDialog
     */
    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    int idsucursal;
    VentanaPrincipal pov;
    int usuario;
    int sesionId;
    InetAddress ip;
    StringBuilder sb;
    
    public CerrarSesion(java.awt.Frame parent, boolean modal, int user, int sesion,VentanaPrincipal pointer) {
       // super(parent, modal);
        initComponents();
        //jCheckBox1.setEnabled(false);
        getRootPane().setDefaultButton(aceptar);
        usuario = user;
        sesionId = sesion;
        pov = pointer;
        String logeado = null;
        extraermac();
        if (VentanaPrincipal.idNivel != 10) {
            try {
                cn = local_connection.getconnect();
                String nombre=(VentanaPrincipal.local)?"nombre||' '||paterno||' '||materno":"concat(nombre,' ',paterno,' ',materno)";
                ps = (PreparedStatement) cn.prepareStatement("SELECT "+nombre+" FROM personas WHERE id_persona = ?");
                ps.setInt(1,usuario);
                rs = ps.executeQuery();
                rs.next();
                if (rs.getString(1).length() >= 15) {
                    logeado = rs.getString(1).substring(0, 15) + "...";
                } else {
                    logeado = rs.getString(1);
                }
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }
        logged.setText(logeado);
    }

    
    public void extraermac() {
      //En esta parte se obtiene la Mac Address de la computadora    
        try {
 ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            } catch (UnknownHostException | SocketException e) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, e);
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked") 
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        logged = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        aceptar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Actualmente esta logueado: ");

        logged.setText("jLabel2");

        jLabel2.setText("Para cerrar sesion ingresa tu contraseña");

        jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPasswordField1ActionPerformed(evt);
            }
        });
        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
        });

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPasswordField1, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aceptar))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(logged, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(logged))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aceptar)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
    
        
        cierreBasico corte = null;
        if (VentanaPrincipal.idNivel == 10) {
            this.dispose();
        } else {
            try {
                ps = local_connection.cn.prepareStatement("SELECT pass FROM personas WHERE id_persona = ?");
                ps.setInt(1,usuario);
                rs = ps.executeQuery();
                rs.next();
                System.out.println(jPasswordField1.getPassword());
                System.out.println(rs.getString(1));
                if (rs.getString(1).equals(String.valueOf(jPasswordField1.getPassword()))) {
                 corte = new cierreBasico(null,true);
                    corte.setVisible(true);
                    ps = (PreparedStatement) cn.prepareStatement("UPDATE sesion SET fin = CURRENT_TIMESTAMP WHERE id = ? ");
                    ps.setInt(1,sesionId);
                    ps.execute();
                    Usuario cambiarUser = new Usuario();
                    cambiarUser.setOtro(false);
                    cambiarUser.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    cambiarUser.setVisible(true);
                    this.dispose();
                    pov.setVisible(false);
                   
                } else {
                    JOptionPane.showMessageDialog(null, "Password incorrecto, intentelo de nuevo");
                    jPasswordField1.setText("");
                    jPasswordField1.requestFocus();
                }
            } catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_aceptarActionPerformed

    private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jPasswordField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField1ActionPerformed

    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
 if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            aceptar.doClick();
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_jPasswordField1KeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JLabel logged;
    // End of variables declaration//GEN-END:variables
}
